//
//  SingleAnalyze.swift
//  MM2
//
//  Created by 李成明 on 2022/1/5.
//

import UIKit

private class OverView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(content)
        content.snp.makeConstraints { make in
            make.center.equalTo(self)
            make.size.equalTo(CGSize(width: 70, height: 24))
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var bgView: UIView = {
        let view = UIView()
        view.backgroundColor = .black
        view.alpha = 0.3
        return view
    }()
    
    private lazy var content:UILabel = {
        let view = UILabel()
        view.font = .systemFont(ofSize: 16)
        view.backgroundColor = .black
        view.text = "正在分析您的颜值～"
        view.textColor = .white
        return view
    }()
}

private class FaceValueView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        layer.masksToBounds = true
        layer.cornerRadius = 10
        
        addsubViews([faceValueLabel, descripLabel])
        faceValueLabel.snp.makeConstraints { make in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(8)
            make.width.equalTo(self)
            make.height.equalTo(200)
        }
        
        descripLabel.snp.makeConstraints { make in
            make.left.right.equalTo(self)
            make.top.equalTo(faceValueLabel.snp.bottom).offset(8)
            make.bottom.equalTo(self)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var descripStr: String = "" {
        didSet {
            descripLabel.text = descripStr
        }
    }
    
    var faceValue: Float = 0.0 {
        didSet {
            let attrStr = NSMutableAttributedString.init(string: String(format: "%.2f", faceValue),attributes: [.font: UIFont.systemFont(ofSize: 16)])
            attrStr.addAttributes([.font: UIFont(name: "Verdana-Italic", size: 150)!], range: NSRange(location: 0, length: faceValue > 10 ? 2 : 1))
            faceValueLabel.attributedText = attrStr
        }
    }
    
    private lazy var faceValueLabel: UILabel = {
        let view = UILabel()
        view.textColor = .initWithRGB(135, 206, 250)
        view.textAlignment = .center
        view.backgroundColor = .white
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 10
        return view
    }()
    
    private lazy var descripLabel: UILabel = {
        let view = UILabel()
        view.font = .systemFont(ofSize: 14)
        view.textColor = .initWithRGB(28, 34, 52)
        view.textAlignment = .center
        return view
    }()
}

class SingleAnalyzeVC: MViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        faceAnalyze()
    }
    
    var image = placeHolderImg
    private var viewModel: FaceUseResultModel?
    private var barrageArray: [SingleAnalyzeBarrageView] = []
    private var contentHeight = kScreenWidth - 96
    
    private lazy var navBar: MNavBar = {
        let view = MNavBar()
        view.title = "颜值测评结果"
        view.back {[weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
        return view
    }()
    
//    private lazy var overView: OverView = OverView.init(frame: view.bounds)

    private lazy var bgView: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "face_anly_bg_img")
        return view
    }()
    
    private lazy var imgView: UIImageView = {
        let view = UIImageView()
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 8
        view.image = image
        return view
    }()
    
    private lazy var dottedView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 10
        view.layer.borderWidth = 1
        view.layer.borderColor = UIColor.initWithRGB(87, 250, 255).cgColor
        return view
    }()
    
    private lazy var heartImgView: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "single_score_heart")
        return view
    }()
    
    private lazy var faceValueView: FaceValueView = {
        let view = FaceValueView()
        return view
    }()
    
    private lazy var faceValueTitleLabel: UILabel = {
        let view = UILabel()
        view.text = "你的颜值分数为:"
        view.font = UIFont(name: "Verdana-Bold", size: 20)
        return view
    }()
    
    private lazy var doubleCatImgView: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "face_result_double")
        return view
    }()
}

extension SingleAnalyzeVC {
    private func setupUI() {
        view.addsubViews([bgView, navBar, dottedView,faceValueTitleLabel, faceValueView, doubleCatImgView])
        dottedView.addsubViews([imgView, heartImgView])
        
        var imgSize = image.size
        let spaceW = kScreenWidth - 96
        
        let scale = (imgSize.width > imgSize.height) ? imgSize.width/(spaceW - 60) : imgSize.height/(spaceW - 60)
        imgSize = CGSize(width: imgSize.width/scale, height: imgSize.height/scale)
        
        bgView.frame = view.bounds
        
        navBar.frame = CGRect(x: 0, y: kStateBarHeight, width: kScreenWidth, height: kNaviBarHeight)
        var y = kStateAndNavH + 20
        dottedView.frame = CGRect(x: 48, y: y, width: contentHeight, height: contentHeight)
        y += (contentHeight + 30)
        faceValueTitleLabel.frame = CGRect(x: 38, y: y, width: contentHeight, height: 25)
        
        y += (25 + 20 + 8 + 200)
        doubleCatImgView.frame = CGRect(x: 48 + 8, y: y - 48, width: 40, height: 40)
        
        imgView.snp.makeConstraints { make in
            make.center.equalTo(dottedView)
            make.size.equalTo(imgSize)
        }
        heartImgView.snp.makeConstraints { make in
            make.right.equalTo(dottedView).offset(-5)
            make.top.equalTo(dottedView).offset(8)
            make.size.equalTo(CGSize(width: 32, height: 32))
        }
        
        faceValueView.snp.makeConstraints { make in
            make.top.equalTo(faceValueTitleLabel.snp.bottom).offset(20)
            make.left.equalTo(view).offset(48)
            make.right.equalTo(view).offset(-48)
            make.bottom.equalTo(view).offset(-20 - kSafeAreaBottomH)
        }
    }
}

extension SingleAnalyzeVC {
    private func faceAnalyze() {
        FaceManager.share.faceDetect(image: image) { num in
            if num > 1{
                self.view.showToast(text: "检测出多张照片，将为你分析第一张")
            }
        } complete: { model in
            self.viewModel = model
            self.analyzeComplete()
        }
    }
    
    private func analyzeComplete() {
        guard let model = viewModel else { return }
        NotificationCenter.default.post(name: NSNotification.Name(notifiRankChange), object: nil)
        setFaceView()
        let locationArray = getBarrageLocation()
        for (index, item) in model.getValueArray().enumerated() {
            guard let location = locationArray[safe: index] else { break }
            let itemView = SingleAnalyzeBarrageView.init(frame: CGRect(x: 0, y: -50, width: 0, height: 0), isLeft: location.isLeft)
            itemView.faceAnalyzeType = item
            barrageArray.append(itemView)
            view.addSubview(itemView)
        }
        
        doAnalyzeAnimation(viewArr: barrageArray, locationArr: getBarrageLocation())
    }
    
    private func setFaceView() {
        faceValueView.faceValue = viewModel?.faceValue ?? 0
        faceValueView.descripStr = "天啦噜，世间竟有如此曼妙的身姿"
    }
    
    private func getBarrageLocation() -> [(y:CGFloat, isLeft: Bool)] {
        let itemH = SingleAnalyzeBarrageView.staticViewHeight
        let space = (contentHeight - itemH*4)/3
        
        var array: [(y:CGFloat, isLeft: Bool)] = []
        var currentH: CGFloat = kStateAndNavH + 20
        for _ in 1...4 {
            array.append((y: currentH, isLeft: true))
            array.append((y: currentH, isLeft: false))
            currentH += (itemH + space)
        }
        
        return array
    }
    
    private func doAnalyzeAnimation(viewArr: [SingleAnalyzeBarrageView], locationArr: [(y:CGFloat,isLeft: Bool)]) {
        guard !viewArr.isEmpty, !locationArr.isEmpty else {
            if let image = Util.rendImageWithView(self.view) {
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
            }
            return
        }
        
        guard let view1 = viewArr.first,  let location1 = locationArr.first, let view2 = viewArr[safe: 1],  let location2 = locationArr[safe: 1] else { return }
        
        view1.frame = CGRect(x: (location1.isLeft ? (-view1.viewWidth) : (kScreenWidth + view1.viewWidth)), y: location1.y, width: view1.viewWidth, height: view1.viewHeight)
        view2.frame = CGRect(x: (location2.isLeft ? (-view2.viewWidth) : (kScreenWidth + view2.viewWidth)), y: location1.y, width: view2.viewWidth, height: view2.viewHeight)
        UIView.animate(withDuration: 0.25) {
            view1.frame = CGRect(x: (location1.isLeft ? 8 : kScreenWidth - 8 - view1.viewWidth), y: location1.y, width: view1.viewWidth, height: view1.viewHeight)
            view2.frame = CGRect(x: (location2.isLeft ? 8 : kScreenWidth - 8 - view2.viewWidth), y: location1.y, width: view2.viewWidth, height: view2.viewHeight)
        } completion: { _ in
            var viewArrCpoy = viewArr
            var locationCopy = locationArr
            viewArrCpoy.removeFirst()
            viewArrCpoy.removeFirst()
            
            locationCopy.removeFirst()
            locationCopy.removeFirst()
            self.doAnalyzeAnimation(viewArr: viewArrCpoy, locationArr: locationCopy)
        }
    }
}
